package com.awspaas.user.apps.processforsap.web;

import com.actionsoft.apps.resource.plugin.profile.DCPluginProfile;
import com.actionsoft.bpms.bo.engine.BO;
import com.actionsoft.bpms.commons.database.RowMap;
import com.actionsoft.bpms.commons.formfile.model.delegate.FormFile;
import com.actionsoft.bpms.commons.mvc.view.ResponseObject;
import com.actionsoft.bpms.server.UserContext;
import com.actionsoft.bpms.server.bind.annotation.Controller;
import com.actionsoft.bpms.server.bind.annotation.Mapping;
import com.actionsoft.bpms.server.fs.DCContext;
import com.actionsoft.bpms.server.fs.dc.DCProfileManager;
import com.actionsoft.sdk.local.SDK;
import com.actionsoft.sdk.local.api.cc.RDSAPI;
import com.alipay.sofa.common.profile.StringUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Controller
public class SapImportModelController {
    private static final String EXTENSION_XLS = ".xls";
    private static final String EXTENSION_XLSX = ".xlsx";

    @Mapping(value = "sap.downloadmodel")
    public static String upFile(UserContext uc, String templateType) {
        ResponseObject responseObject = ResponseObject.newOkResponse("下载成功");
        String sessionId = uc.getSessionId();
        Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        try {
            BO importModel = SDK.getBOAPI().query("BO_EU_MM_DCMB").addQuery("MODEL_ID = '" + templateType + "'", null).detail();//导入模板表
            if (importModel != null) {
                String fileModel = importModel.getString("MODEL_FILE");
                if (fileModel != null && !"".equals(fileModel)) { //如果文件不为空
                    /** 获取对应附件 */
                    List<FormFile> file_model = SDK.getBOAPI().getFiles(importModel.getId(), "MODEL_FILE");
                    if (templateType.equals("fi004")||templateType.equals("xxbc")||templateType.equals("xxxg")||templateType.equals("dybg")) {
                        InputStream file = null;
                        FileOutputStream excelFile = null;
                        try {

                            file = SDK.getBOAPI().getFile(file_model.get(0).getId());
                            /** 将对应附件解析 */
                            Workbook wb = null;
                            if (fileModel.endsWith(EXTENSION_XLS)) {
                                wb = new HSSFWorkbook(file);
                            } else if (fileModel.endsWith(EXTENSION_XLSX)) {
                                wb = new XSSFWorkbook(file);
                            }
                            if (wb != null) {
                                Sheet sheet = wb.getSheetAt(templateType.equals("fi004")?5:1);

                                String sql = "SELECT VALUE,TEXT FROM SAP_DICTIONARY WHERE TYPE = '成本中心'";
                                String rdsId = SDK.getRuleAPI().executeAtScript("@getSapParamas(SAP_MID_ID)");
                                RDSAPI rdsapi = SDK.getCCAPI().getRDSAPI(rdsId);
                                List<RowMap> list = rdsapi.getMaps(sql);
                                //获取SAP部门编码数据
                                for (int i = 0; i < list.size(); i++) {
                                    //获取行数据
                                    RowMap bo = list.get(i);
                                    String value = bo.getString("VALUE");

                                    Row row = sheet.createRow(i+1);
                                    Cell cellType1 = row.createCell(0);
                                    cellType1.setCellValue(value);

                                    Cell cellType2 = row.createCell(1);
                                    cellType2.setCellValue(bo.getString("TEXT"));

                                    Cell cellType3= row.createCell(2);
                                    if (value.contains("FE")){
                                        cellType3.setCellValue("FE00");
                                    }else if (value.contains("FS")){
                                        cellType3.setCellValue("FS00");
                                    }

                                }
                            }
                            long times = System.currentTimeMillis();
                            DCPluginProfile dcProfile = DCProfileManager.getDCProfile("com.awspaas.user.apps.processforsap", "mmData");
                            DCContext dcContext = new DCContext(uc, dcProfile, "com.awspaas.user.apps.processforsap", "mmData11", times + "", "导入模板" + EXTENSION_XLSX);
                            String path = dcContext.getPath();
                            File file1 = new File(path);
                            file1.mkdir();
                            excelFile = new FileOutputStream(dcContext.getFilePath());
                            wb.write(excelFile);
                            excelFile.flush();
                            String downloadURL = dcContext.getDownloadURL();
                            String replace = downloadURL.replace("sid=", "sid=" + sessionId + "");
                            responseObject.setData(replace);
                        } catch (Exception e) {
                            e.printStackTrace();
                            responseObject.setData("模板生成失败！");
                        } finally {
                            if (file != null) {
                                try {
                                    file.close();
                                } catch (IOException ioException) {
                                    ioException.printStackTrace();
                                }
                            }
                            if (excelFile != null) {
                                try {
                                    excelFile.close();
                                } catch (IOException ioException) {
                                    ioException.printStackTrace();
                                }
                            }
                        }
                    } else {
                        DCContext dc = SDK.getBOAPI().getFileDCContext(file_model.get(0));//查询对应dc上下文
                        String downloadURL = SDK.getPortalAPI().getPortalUrl() + "/r/" + dc.getDownloadURL().replace("./", "").replace("sid=", "sid=" + uc.getSessionId());
                        String replace = downloadURL.replace("sid=", "sid=" + sessionId + "");
                        responseObject.setData(replace);
                    }
                }
            } else {
                responseObject.err("模板生成失败！");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return responseObject.toString();
    }
}
